import pandas as pd
import matplotlib.pyplot as plt
from statsmodels.tsa.seasonal import seasonal_decompose
import numpy as np
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_absolute_error, mean_squared_error
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, LSTM, Dropout


# 读取数据
data = pd.read_excel('temperature_data-2023-2024.xlsx', parse_dates=['date'], index_col='date')
# 统计描述
print("统计描述:")
print(data.describe())

# 缺失值处理
print("缺失值检查:")
print(data.isnull().sum())

# 如果有缺失值，使用向前填充方法进行处理
data.fillna(method='ffill', inplace=True)
print("缺失值处理后:")
print(data.isnull().sum())

# 数据趋势和季节性分析
# 移动平均线
data['temperature_MA'] = data['temperature'].rolling(window=24).mean()

plt.figure(figsize=(14, 7))
plt.rcParams['font.sans-serif'] = 'SimHei'
plt.plot(data['temperature'], label='气温')
plt.plot(data['temperature_MA'], label='24小时移动平均线', color='orange')
plt.xlabel('日期')
plt.ylabel('温度 (°C)')
plt.title('温度和24小时移动平均线')
plt.legend()
plt.show()

# 季节性分解
decomposition = seasonal_decompose(data['temperature'], model='additive', period=24)
fig = decomposition.plot()
fig.set_size_inches(14, 8)
plt.xlabel('日期')
plt.ylabel('温度 (°C)')
plt.title('温度季节性分解')
plt.show()

# 数据标准化
scaler = MinMaxScaler(feature_range=(0, 1))
temperature_scaled = scaler.fit_transform(data['temperature'].values.reshape(-1, 1))
# 打印标准化后的数据
print("标准化后的数据:")
print(temperature_scaled)
# 创建数据集
def create_dataset(data, time_step=1):
    X, y = [], []
    for i in range(len(data) - time_step - 1):
        X.append(data[i:(i + time_step), 0])
        y.append(data[i + time_step, 0])
    return np.array(X), np.array(y)

time_step = 10
X, y = create_dataset(temperature_scaled, time_step)
X = X.reshape(X.shape[0], X.shape[1], 1)

# 数据分割
train_size = int(len(X) * 0.8)
X_train, X_test = X[:train_size], X[train_size:]
y_train, y_test = y[:train_size], y[train_size:]

# 构建神经网络模型
model = Sequential()
model.add(LSTM(50, return_sequences=True, input_shape=(time_step, 1)))
model.add(LSTM(50, return_sequences=False))
model.add(Dropout(0.2))
model.add(Dense(25))
model.add(Dense(1))

model.compile(optimizer='adam', loss='mean_squared_error')

# 训练模型
history = model.fit(X_train, y_train, batch_size=1, epochs=20, validation_data=(X_test, y_test))
# 保存模型
model.save('temperature_prediction_model.h5')
# 预测
train_predict = model.predict(X_train)
test_predict = model.predict(X_test)

# 反标准化预测值
train_predict = scaler.inverse_transform(train_predict)
test_predict = scaler.inverse_transform(test_predict)

# 反标准化真实值
y_train = scaler.inverse_transform(y_train.reshape(-1, 1))
y_test = scaler.inverse_transform(y_test.reshape(-1, 1))

# 计算误差
train_mae = mean_absolute_error(y_train, train_predict)
train_rmse = np.sqrt(mean_squared_error(y_train, train_predict))
test_mae = mean_absolute_error(y_test, test_predict)
test_rmse = np.sqrt(mean_squared_error(y_test, test_predict))

print(f'训练集 MAE: {train_mae:.3f}')
print(f'训练集 RMSE: {train_rmse:.3f}')
print(f'测试集 MAE: {test_mae:.3f}')
print(f'测试集 RMSE: {test_rmse:.3f}')

# 可视化损失曲线
plt.figure(figsize=(12, 6))
plt.plot(history.history['loss'], label='训练集损失')
plt.plot(history.history['val_loss'], label='验证集损失')
plt.xlabel('Epoch')
plt.ylabel('损失')
plt.title('训练和验证损失')
plt.legend()
plt.show()

# 可视化预测结果
plt.figure(figsize=(12, 6))
plt.plot(data.index[:len(y_train)], y_train, label='真实训练数据')
plt.plot(data.index[len(y_train):len(y_train) + len(y_test)], y_test, label='真实测试数据')
plt.plot(data.index[:len(train_predict)], train_predict, label='训练集预测')
plt.plot(data.index[len(train_predict):len(train_predict) + len(test_predict)], test_predict, label='测试集预测')
plt.xlabel('日期')
plt.ylabel('温度 (°C)')
plt.title('温度预测')
plt.legend()
plt.show()

# 真实值与预测值对比图
plt.figure(figsize=(12, 6))
plt.scatter(y_test, test_predict, label='测试数据')
plt.xlabel('真实值')
plt.ylabel('预测值')
plt.title('真实值 vs 预测值')
plt.legend()
plt.show()
